package com.woniuxy.caradmin.controller;

import com.woniuxy.caradmin.entity.pojo.NavNode;
import com.woniuxy.caradmin.entity.pojo.NavNodeBuilder;
import com.woniuxy.caradmin.entity.pojo.Permission;
import com.woniuxy.caradmin.entity.pojo.User;
import com.woniuxy.caradmin.exception.CarException;
import com.woniuxy.caradmin.service.PermissionService;
import com.woniuxy.caradmin.service.UserService;
import com.woniuxy.caradmin.util.Constaint;
import com.woniuxy.caradmin.util.R;
import com.woniuxy.caradmin.util.ResultCode;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


@RestController
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    @GetMapping("/login")
    @ApiOperation("通过账号密码登录")
    public R selectPhoAndPsw(String telephone, String password, HttpSession session){
        User user = userService.selectPhoAndPsw(telephone, password);
        if(user !=null){
            session.setAttribute("USER_SESSION",user);
            return R.ok().code(ResultCode.LOGINSUCCESS).message(Constaint.LOGINSUCCESS);
        }else {
            throw new CarException(ResultCode.LOGINFIAIL,Constaint.LOGINFIAIL);
        }
    }

    @ApiOperation("首页菜单")
    @GetMapping("/indexNavMenu")
    public List<NavNode> indexNavsMenu(HttpSession session){
        User user_session =(User) session.getAttribute("USER_SESSION");
        System.out.println("********"+user_session.getId());
        List<NavNode> navNodes=new ArrayList<>();
        if(user_session!=null){
            List<Permission> permissions = permissionService.selectPermissionsByUid(user_session.getId());
            if(permissions!=null){
                for(Permission permission:permissions){
                    NavNode navNode=new NavNode();
                    navNode.setId(permission.getId());
                    navNode.setPid(permission.getPid());
                    navNode.setTitle(permission.getName());
                    navNode.setIcon(permission.getIcon());
                    navNode.setHref(permission.getHref());
                    System.out.println("******----"+permission.getOpen());
                    if(permission.getOpen()==1){
                        navNode.setSpread(true);
                    }else if(permission.getOpen()==0){
                        navNode.setSpread(false);
                    }
                    navNodes.add(navNode);
                }
            }
        }
        List<NavNode> newNavNodes = NavNodeBuilder.builder(navNodes, 1);
        return newNavNodes;
    }


}
